#
# @lc app=leetcode.cn id=1854 lang=python
#
# [1854] 人口最多的年份
#

# @lc code=start
class Solution(object):
    def maximumPopulation(self, logs):
        """
        :type logs: List[List[int]]
        :rtype: int
        """
        changes = []
        
        # 添加出生和死亡前一年的标记
        for birth, death in logs:
            print(birth, death)
            changes.append((birth, 1))  # 出生时人口 +1
            changes.append((death - 1, -1))  # 死亡前一年人口 -1
        print(changes)
        # 按照年份排序
        changes.sort(key=lambda x: (x[0], -x[1]))
        
        # 初始化变量
        current_population = max_population = 0
        earliest_year = 0
        
        # 遍历变化列表
        for year, delta in changes:
            current_population += delta
            if current_population > max_population:
                max_population = current_population
                earliest_year = year
        
        return earliest_year
# @lc code=end

